package setting.itheima.com.a01_guanli.db.dao;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import setting.itheima.com.a01_guanli.db.StudentDbOpenHelper;
import setting.itheima.com.a01_guanli.domain.Student;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by asus on 2017/11/23.
 */

public class StudentDao {

    StudentDbOpenHelper helper;

    //获得helper里面的应用
    public StudentDao(Context context){
        helper = new StudentDbOpenHelper(context);
    }

    //如果做增删改操作，那么就getWritableDatabase()，表示获得一个可写的数据库
    public void insert(String name,String sex){

        SQLiteDatabase db = helper.getWritableDatabase();
        String string = new String("insert into students values(null,?,?)");
        //insert into students values()
        //执行sql语句
        db.execSQL(string,new Object[]{name,sex});//Object 任意的类型数据 数组传递到name,sex中去

        //释放资源,关闭
        db.close();
    }
    public void delete(String name){

        SQLiteDatabase db = helper.getWritableDatabase();
        String string = new String("delete from students where name=?");
        //delete from student where name=?
        db.execSQL(string,new Object[]{name});
        db.close();
    }
    public void update(String name,String sex){

        SQLiteDatabase db = helper.getWritableDatabase();
        String string = new String("update students set sex =? where name =?");
        //update students set sex =? where name =?;
        db.execSQL(string,new Object[]{sex,name});
        db.close();
    }
    public String findOne(String name){

        //获得一个可读的数据库
        SQLiteDatabase db = helper.getReadableDatabase();
        String string = new String("select * from students where name=?");
        //db.execSQL(string,new Object[]{name});  没有返回值
        Cursor cursor = db.rawQuery(string,new String[]{name});

        String sex = null;
        if (cursor.moveToNext()){
            sex = cursor.getString(0);
        }

        return sex;
    }

    //查询返回所有的学生的信息
    public List<Student> getAll() {

        //查询所有的学生的信息
        SQLiteDatabase db = helper.getReadableDatabase();

        Cursor cursor = db.rawQuery("select * from students",null);

        List<Student> list = new ArrayList<Student>();
        Student student = null;
        while (cursor.moveToNext()){
            int id = cursor.getInt(0);
            String name = cursor.getString(1);
            String sex = cursor.getString(2);

            student = new Student(id,name,sex);
            list.add(student);
        }

        return list;
    }
}
